package cn.com.pansky.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import cn.com.pansky.util.EncryptionUtils;

public class WXQuery {
	
	public static void main(String[] args) {
		try {
			URL url = new URL("https://api.mch.weixin.qq.com/pay/orderquery");
	        URLConnection con = url.openConnection();
	        con.setDoOutput(true);
	        con.setRequestProperty("Pragma:", "no-cache");
	        con.setRequestProperty("Cache-Control", "no-cache");
	        con.setRequestProperty("Content-Type", "text/xml");
	
	        OutputStreamWriter out = new OutputStreamWriter(con
	                .getOutputStream());    
	        Map<String, String[]> paramsMap = new HashMap<String, String[]>();
	        StringBuilder sb = new StringBuilder();
	        sb.append("<xml>");
	        sb.append("    <appid>wx2421b1c4370ec43b</appid>");		//应用ID
	        paramsMap.put("appid", new String[] { "wx2421b1c4370ec43b" });
	        sb.append("    <mch_id>10000100</mch_id>");				//商户号
	        paramsMap.put("mch_id", new String[] { "10000100" });
	        sb.append("    <transaction_id>123456</transaction_id>");		//微信订单号
	        paramsMap.put("transaction_id", new String[] { "123456" });
	        sb.append("    <out_trade_no>12345</out_trade_no>");		//商户系统内部订单号
	        paramsMap.put("out_trade_no", new String[] { "12345" });
	        sb.append("    <nonce_str>C380BEC2BFD727A4B6845133519F3AD6</nonce_str>");			//随机字符串
	        paramsMap.put("nonce_str", new String[] { "C380BEC2BFD727A4B6845133519F3AD6" });
	        String sign = EncryptionUtils.makeSignature(paramsMap, "pansky");
	        sb.append("    <sign>"+sign+"</sign>");		//签名
	        sb.append("</xml>");
	        String xmlInfo = sb.toString();
	        out.write(new String(xmlInfo.getBytes("ISO-8859-1")));
	        out.flush();
	        out.close();
	        BufferedReader br = new BufferedReader(new InputStreamReader(con
	                .getInputStream()));
	        String line = "";
	        String result = "";
	        for (line = br.readLine(); line != null; line = br.readLine()) {
	            result = result + line;
	        }
	        System.out.println(result);
	        String return_code = result.split("<return_code>")[1].split("</return_code>")[0];
	        boolean boo = return_code.contains("SUCCESS");
	        if (boo) {
				//查询成功
	        	//返回模板：
				//<xml>
				//   <return_code><![CDATA[SUCCESS]]></return_code>
				//   <return_msg><![CDATA[OK]]></return_msg>
				//   <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
				//   <mch_id><![CDATA[10000100]]></mch_id>
				//   <device_info><![CDATA[1000]]></device_info>
				//   <nonce_str><![CDATA[TN55wO9Pba5yENl8]]></nonce_str>
				//   <sign><![CDATA[BDF0099C15FF7BC6B1585FBB110AB635]]></sign>
				//   <result_code><![CDATA[SUCCESS]]></result_code>
				//   <openid><![CDATA[oUpF8uN95-Ptaags6E_roPHg7AG0]]></openid>
				//   <is_subscribe><![CDATA[Y]]></is_subscribe>
				//   <trade_type><![CDATA[APP]]></trade_type>
				//   <bank_type><![CDATA[CCB_DEBIT]]></bank_type>
				//   <total_fee>1</total_fee>
				//   <fee_type><![CDATA[CNY]]></fee_type>
				//   <transaction_id><![CDATA[1008450740201411110005820873]]></transaction_id>
				//   <out_trade_no><![CDATA[1415757673]]></out_trade_no>
				//   <attach><![CDATA[订单额外描述]]></attach>
				//   <time_end><![CDATA[20141111170043]]></time_end>
				//   <trade_state><![CDATA[SUCCESS]]></trade_state>
				//</xml>
	        	String appid = result.split("<appid>")[1].split("</appid>")[0].split("CDATA")[1];
	        	appid = appid.substring(1, appid.length()-3);
	        	String mch_id = result.split("<mch_id>")[1].split("</mch_id>")[0].split("CDATA")[1];
	        	mch_id = mch_id.substring(1,mch_id.length()-3);
	        	String nonce_str = result.split("<nonce_str>")[1].split("</nonce_str>")[0].split("CDATA")[1];
	        	nonce_str = nonce_str.substring(1,nonce_str.length()-3);
	        	String sign_ = result.split("<sign>")[1].split("</sign>")[0].split("CDATA")[1];
	        	sign_ = sign_.substring(1,sign_.length()-3);
	        	String result_code = result.split("<result_code>")[1].split("</result_code>")[0].split("CDATA")[1];
	        	result_code = result_code.substring(1,result_code.length()-3);
	        	String trade_state = "";//交易状态
											//SUCCESS—支付成功
											//REFUND—转入退款
											//NOTPAY—未支付
											//CLOSED—已关闭
											//REVOKED—已撤销（刷卡支付）
											//USERPAYING--用户支付中
											//PAYERROR--支付失败(其他原因，如银行返回失败)
	        	String trade_type = "";	//调用接口提交的交易类型
	        	String openid = "";		//用户在商户appid下的唯一标识
	        	String total_fee = "";	//交易金额，单位是分
	        	if ("SUCCESS".equals(result_code)) {
	        		openid = result.split("<openid>")[1].split("</openid>")[0].split("CDATA")[1];
	        		openid = openid.substring(1,openid.length()-3);
	        		trade_state = result.split("<trade_state>")[1].split("</trade_state>")[0].split("CDATA")[1];
	        		trade_state = trade_state.substring(1,trade_state.length()-3);
	        		trade_type = result.split("<trade_type>")[1].split("</trade_type>")[0].split("CDATA")[1];
	        		trade_type = trade_type.substring(1,trade_type.length()-3);
	        		total_fee = result.split("<total_fee>")[1].split("</total_fee>")[0].split("CDATA")[1];
	        		total_fee = total_fee.substring(1,total_fee.length()-3);
				}
	        	//TODO
			} else {
				//查询失败
				System.out.println(result);
			}
		} catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	
}
